var mysql      = require('mysql');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var userSQL = require('./Usersql');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

var pool = mysql.createPool({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'test'
});

// var connection = mysql.createConnection();

//api路由
app.post('/api/saveNameAndToken', function (req, res) {
    let name = req.query.name || req.body.name,token = req.query.token || req.body.token;
    console.log(req.body);
    console.log(req.query);
    console.log(req.params);
    // let sql = `INSERT INTO user_face_token(face_token,name) value ("${token}","${name}")`;
    // console.log(sql);
    let result = 0;
    // connection.connect();
    pool.getConnection(function(err,connection){
        connection.query(userSQL.insert,[token,name], function(err, rows, fields) {
            if (err) console.log(err);
            console.log('The result is: ', rows.affectedRows);
            if(rows) result =  rows.affectedRows;
            res.json({result:result});
        });
        connection.release();
    });
    
    
    
});
app.get('/api/getNamebyToken', function (req, res) {
   
    let name,token = req.query.token;
    // let sql = `SELECT face_token,name FROM user_face_token WHERE face_token = "${token}"`;
    // console.log(sql);
    // connection.connect();
    pool.getConnection(function(err,connection){
        connection.query(userSQL.getNameByToken,[token], (err, rows, fields) =>{
            if (err) console.log(err);
            let face_token;
            if(rows[0]) {
                name = rows[0].name;
                face_token = rows[0].face_token;
            }
            console.log('The result is: ', name ,face_token);
            res.json({name:name});
        });
        connection.release();
    });
    
   
});

var server = app.listen(8080, function () {
    var host = server.address().address;
    var port = server.address().port;
  
    console.log('Example app listening at http://%s:%s', host, port);
  });